import Utils from '../base/utils.js'

export default class SprayPaint {
  constructor() {
    this.canvas = wx.createCanvas()
    this.context = this.canvas.getContext('2d')
    this.imagedata = this.context.getImageData(0, 0, this.canvas.width, this.canvas.height)
    this.pixels = this.imagedata.data
    this.brushSize = 25
    this.brushDensity = 50
    this.brushColor
    this.sprites = []
    this.loop = this.drawFrame.bind(this)
    this.touchHandler = this.touchEventHandler.bind(this)

    wx.onTouchStart((e) => {
      this.brushColor = Utils.parseColor(Math.random() * 0xFFFFFF, true)
      wx.onTouchMove(this.touchHandler)
    })

    wx.onTouchEnd((e) => {
      wx.offTouchMove(this.touchHandler)
    })
  }

  touchEventHandler(e) {
    for (let i = 0; i < this.brushDensity; ++i) {
      let angle = Math.random() * Math.PI * 2,
        radius = Math.random() * this.brushSize,
        xPos = (e.touches[0].clientX + Math.cos(angle) * radius) | 0,
        yPos = (e.touches[0].clientY + Math.sin(angle) * radius) | 0,
        offset = (xPos + yPos * this.imagedata.width) * 4

        // pixel component colors : r,g,b,a (0-255)
        this.pixels[offset] = this.brushColor >> 16 & 0xFF     // red
        this.pixels[offset + 1] = this.brushColor >> 8 & 0xFF  // green
        this.pixels[offset + 2] = this.brushColor & 0xFF        // blue
        this.pixels[offset + 3] = 255                          // alpha
    }

    this.context.putImageData(this.imagedata, 0, 0)
  }

  addChild(sprite) {
    if (sprite) {
      this.sprites.push(sprite)
    }
  }

  drawFrame() {
    requestAnimationFrame(this.loop)
    // this.context.clearRect(0, 0, this.canvas.width, this.canvas.height)
    for (let sprite of this.sprites) {
      sprite.draw(this.context)
    }
  }
}